import { app, BrowserWindow, dialog, ipcMain, shell } from 'electron';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import axios from 'axios';
import https from 'https';
import { exec, execFile } from 'child_process';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

let mainWindow: BrowserWindow | null = null;
// Electron 加载 preload 文件，必须是编译后的 JS

const isDev = !app.isPackaged;
const preloadPath = path.join(__dirname, 'preload.mjs');


function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    minWidth: 900,  // 最小宽度
    minHeight: 800, // 最小高度
    frame: false, // 移除原生窗口框架
    webPreferences: {
      preload: preloadPath, // 一定要正确路径
      nodeIntegration: false,
      contextIsolation: true, // 必须开
    },
  });
  // 隐藏默认菜单栏
  mainWindow.setMenuBarVisibility(false); // ✅ 这一行
  if (process.env.VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL);
  } else {
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'));
  }
  if (mainWindow !== null) {
    ipcMain.on('minimize-window', () => {
      mainWindow?.minimize();
    });

    ipcMain.on('toggle-maximize', () => {
      if (mainWindow !== null && mainWindow.isMaximized()) {
        mainWindow.unmaximize();
      } else {
        mainWindow?.maximize();
      }
    });

    ipcMain.on('close-window', () => {
      mainWindow?.close();
    });

  }
}

app.on('ready', createWindow);

// IPC 处理选择目录
ipcMain.handle('select-directory', async () => {
  if (!mainWindow) return null;
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openDirectory'],
  });
  if (result.canceled) return null;
  return result.filePaths[0];
});




// 支持的视频扩展名
const VIDEO_EXTS = ['.mp4', '.mkv', '.avi', '.mov'];
const POSTER_NAMES = ['poster.jpg', 'poster.png'];
const BACKDROP_NAMES = ['backdrop.jpg', 'backdrop.png'];

ipcMain.handle('get-movie-list', async (_event, dirPath: string) => {
  if (!dirPath) return [];

  try {
    const entries = fs.readdirSync(dirPath, { withFileTypes: true });
    const movies: {
      name: string;
      path: string;
      cover?: string;       // 封面 base64
      backdrop?: string;    // 背景 base64
      details?: any;        // 本地 JSON 数据
    }[] = [];

    for (const entry of entries) {
      if (!entry.isDirectory()) continue;

      const movieDir = path.join(dirPath, entry.name);
      const files = fs.readdirSync(movieDir);

      // 查找视频文件
      const videoFile = files.find(f => VIDEO_EXTS.includes(path.extname(f).toLowerCase()));
      if (!videoFile) continue;

      let coverBase64: string | undefined;
      let backdropBase64: string | undefined;

      // 查找封面文件
      const posterFile = POSTER_NAMES.find(name => files.includes(name));
      if (posterFile) {
        const posterPath = path.join(movieDir, posterFile);
        const ext = path.extname(posterPath).slice(1);
        const buffer = fs.readFileSync(posterPath);
        coverBase64 = `data:image/${ext};base64,${buffer.toString('base64')}`;
      }

      // 查找背景文件
      const backdropFile = files.find(f => f.startsWith('backdrop'));
      if (backdropFile) {
        const backdropPath = path.join(movieDir, backdropFile);
        const ext = path.extname(backdropPath).slice(1);
        const buffer = fs.readFileSync(backdropPath);
        backdropBase64 = `data:image/${ext};base64,${buffer.toString('base64')}`;
      }

      // 读取本地 JSON 数据（movie.json）
      let details: any = undefined;
      const jsonFile = path.join(movieDir, 'movie.json');
      if (fs.existsSync(jsonFile)) {
        try {
          const raw = fs.readFileSync(jsonFile, 'utf-8');
          details = JSON.parse(raw);
        } catch (e) {
          console.warn(`读取 ${entry.name}/movie.json 失败`, e);
        }
      }

      movies.push({
        name: entry.name,
        path: path.join(movieDir, videoFile),
        cover: coverBase64,
        backdrop: backdropBase64,
        details,
      });
    }

    return movies;
  } catch (err) {
    console.error('读取电影目录失败:', err);
    return [];
  }
});




// 监听渲染进程发来的请求
const ACCESS_TOKEN = 'eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIwYjdmNWUzNmM2NDU3MDMyMjljYzc5ODhiOGJjY2ZjZCIsIm5iZiI6MTc1NjkyNDY5NS4wODQsInN1YiI6IjY4Yjg4YjE3NTc1YTFlZmRiNTliYWZhNCIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.i7j85IXQg4lwi-OHl8Qqx6vpVt70vghW2OpIWKrOFBE'
ipcMain.handle('search-movies', async (event, query) => {
  try {
    const searchUrl = 'https://api.themoviedb.org/3/search/movie';
    const response = await axios.get(searchUrl, {
      headers: {
        'Authorization': `Bearer ${ACCESS_TOKEN}`,
        'Accept': 'application/json'
      },
      params: {
        query: query,
        language: 'zh-CN'
      }
    });
    return response.data.results; // 返回搜索结果
  } catch (error) {
    if (axios.isAxiosError(error)) {
      console.error('API 请求出错:', error);
      return { error: true, message: 'API request failed' };
    }
    return { error: true, message: 'Unknown error' };
  }
});

// 处理获取电影详情的请求
ipcMain.handle('get-movie-details', async (event, movieId) => {
  try {
    const detailsUrl = `https://api.themoviedb.org/3/movie/${movieId}`;
    const response = await axios.get(detailsUrl, {
      headers: { 'Authorization': `Bearer ${ACCESS_TOKEN}` },
      params: { language: 'zh-CN' }
    });
    // 返回电影详情数据
    return response.data;
  } catch (error) {
    console.error('API 详情请求出错:', error);
    return null;
  }
});


ipcMain.handle('download-image', async (_event, url: string) => {
  const ext = path.extname(url).split('?')[0] || '.jpg';
  const fileName = path.basename(url).split('?')[0];
  const saveDir = path.join(app.getPath('userData'), 'tmdb_cache');
  if (!fs.existsSync(saveDir)) fs.mkdirSync(saveDir, { recursive: true });

  const savePath = path.join(saveDir, fileName);

  if (fs.existsSync(savePath)) return savePath; // 已下载直接返回

  return new Promise<string>((resolve, reject) => {
    const file = fs.createWriteStream(savePath);
    https
      .get(url, (res) => {
        res.pipe(file);
        file.on('finish', () => {
          file.close();
          resolve(savePath);
        });
      })
      .on('error', (err) => {
        fs.unlinkSync(savePath);
        reject(err);
      });
  });
});

ipcMain.handle('download-image-base64', async (_event, url: string) => {
  return new Promise<string>((resolve, reject) => {
    https.get(url, (res) => {
      const chunks: Buffer[] = []
      res.on('data', (chunk) => chunks.push(chunk))
      res.on('end', () => {
        const buffer = Buffer.concat(chunks)
        const base64 = `data:image/jpeg;base64,${buffer.toString('base64')}`
        resolve(base64)
      })
    }).on('error', reject)
  })
})


ipcMain.handle('save-movie-details', async (_event, movieId, movieDir: string) => {
  try {
    // 0. 查询电影详情
    const detailsUrl = `https://api.themoviedb.org/3/movie/${movieId}`;
    const response = await axios.get(detailsUrl, {
      headers: { 'Authorization': `Bearer ${ACCESS_TOKEN}` },
      params: { language: 'zh-CN' }
    });
    const movieData = response.data;

    // 1. 保存电影 JSON
    const jsonPath = path.join(movieDir, 'movie.json');
    fs.writeFileSync(jsonPath, JSON.stringify(movieData, null, 2), 'utf-8');

    // 2. 下载封面
    let posterLocalPath = '';
    if (movieData.poster_path) {
      const url = `https://image.tmdb.org/t/p/w500${movieData.poster_path}`;
      const ext = path.extname(url) || '.jpg';
      posterLocalPath = path.join(movieDir, 'poster' + ext);

      await new Promise<void>((resolve, reject) => {
        const file = fs.createWriteStream(posterLocalPath);
        https.get(url, (res) => {
          res.pipe(file);
          file.on('finish', () => {
            file.close();
            resolve();
          });
        }).on('error', (err) => {
          if (fs.existsSync(posterLocalPath)) fs.unlinkSync(posterLocalPath);
          reject(err);
        });
      });
    }

    // 3. 下载背景图（backdrop）
    let backdropLocalPath = '';
    if (movieData.backdrop_path) {
      const url = `https://image.tmdb.org/t/p/w1280${movieData.backdrop_path}`;
      const ext = path.extname(url) || '.jpg';
      backdropLocalPath = path.join(movieDir, 'backdrop' + ext);

      await new Promise<void>((resolve, reject) => {
        const file = fs.createWriteStream(backdropLocalPath);
        https.get(url, (res) => {
          res.pipe(file);
          file.on('finish', () => {
            file.close();
            resolve();
          });
        }).on('error', (err) => {
          if (fs.existsSync(backdropLocalPath)) fs.unlinkSync(backdropLocalPath);
          reject(err);
        });
      });
    }

    return { success: true, posterLocalPath, backdropLocalPath };
  } catch (err: any) {
    console.error('保存电影详情失败', err);
    return { success: false, error: err.message };
  }
});



// 假设 PotPlayer 安装在默认路径，如果不同请修改
const POTPLAYER_PATH = `D:\\software\\PotPlayer\\PotPlayerMini64.exe`;

ipcMain.handle('play-movie', async (_event, moviePath: string) => {
  return new Promise((resolve, reject) => {
    if (!moviePath) return reject(new Error('电影路径为空'));

    execFile(POTPLAYER_PATH, [moviePath], (err) => {
      if (err) {
        console.error('启动 PotPlayer 失败:', err);
        reject(err);
      } else {
        resolve(true);
      }
    });
  });
});
// 获取电影目录下的视频文件
ipcMain.handle('get-movie-files', async (_event, movieDir: string) => {
  try {
    const files = fs.readdirSync(movieDir);
    return files.filter(f => VIDEO_EXTS.includes(path.extname(f).toLowerCase()));
  } catch (err) {
    console.error('读取电影文件列表失败:', err);
    return [];
  }
});



// 电影信息 JSON 文件名
const MOVIE_JSON = 'movie.json';
ipcMain.handle('read-movie-details', async (_event, movieDir: string) => {
  try {
    if (!fs.existsSync(movieDir)) return null;

    // 读取 movie.json
    const jsonPath = path.join(movieDir, MOVIE_JSON);
    let movieData: any = {};
    if (fs.existsSync(jsonPath)) {
      const raw = fs.readFileSync(jsonPath, 'utf-8');
      movieData = JSON.parse(raw);
    }

    // 封面
    let posterPath: string | undefined;
    for (const name of POSTER_NAMES) {
      const p = path.join(movieDir, name);
      if (fs.existsSync(p)) {
        const ext = path.extname(p).slice(1); // jpg/png
        const buffer = fs.readFileSync(p);
        posterPath = `data:image/${ext};base64,${buffer.toString('base64')}`;
        break;
      }
    }
    // 背景图
    let backdropPath: string | undefined;
    for (const name of BACKDROP_NAMES) {
      const p = path.join(movieDir, name);
      if (fs.existsSync(p)) {
        const ext = path.extname(p).slice(1); // jpg/png
        const buffer = fs.readFileSync(p);
        backdropPath = `data:image/${ext};base64,${buffer.toString('base64')}`;
        break;
      }
    }

    return {
      ...movieData,
      posterPath, // Base64 封面
      backdropPath, // Base64 背景图
    };
  } catch (err) {
    console.error('读取电影详情失败:', err);
    return null;
  }
});



// 浏览器打开
ipcMain.on('open-external', (event, url) => {
  shell.openExternal(url);
});



// 打开文件夹
ipcMain.handle('open-folder', async (_event, dir: string) => {
  if (fs.existsSync(dir)) {
    shell.openPath(dir); // 在资源管理器里打开
  } else {
    throw new Error('目录不存在: ' + dir);
  }
});



// 运行字幕处理
ipcMain.handle('run-subtitle-bat', async (event, movieDir: string) => {
  return new Promise((resolve, reject) => {
    const batPath = path.join(movieDir, 'run_ass_process.bat');
    if (!fs.existsSync(batPath)) return reject('bat 文件不存在');

    // 使用 cmd /c 执行 .bat，避免 spawn EINVAL
    execFile('cmd', ['/c', batPath], { cwd: movieDir, windowsHide: true }, (error, stdout, stderr) => {
      if (error) return reject(stderr || error.message);
      resolve(stdout || '运行成功');
    });
  });
});